package com.mock.ems.controller;

import com.jfinal.aop.Before;
import com.jfinal.core.Controller;
import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.Page;
import com.jfinal.plugin.activerecord.Record;
import com.jfinal.plugin.activerecord.tx.Tx;
import com.mock.base.util.DateUtil;
import com.mock.base.util.NumberUtil;
import com.mock.base.util.StringUtil;
import com.mock.ems.common.JsonResult;

import java.math.BigDecimal;
import java.util.*;

public class GroupPurchaseController extends Controller{

    public void index(){
        renderJsp("/page/grouppurchase/group_purchase_list.jsp");
    }

    public void edit(){
        Record record = Db.findById("t_group_purchase_param", getPara("groupPurchaseParamId"));
        if (null != record) {
            this.setAttr("groupPurchaseParam", record.getColumns());
        }
        renderJsp("/page/grouppurchase/group_purchase_add.jsp");
    }

    public void pagination() {
        // 拼装查询条件
        int pageNumber = this.getParaToInt("pageNumber");
        int pageSize = this.getParaToInt("pageSize");

        StringBuilder exceptSelectSQL = new StringBuilder(" from t_group_purchase_param where 1 = 1 ");
        List<Object> params = new ArrayList<Object>();

        String title = getPara("title");
        String discount = getPara("discount");

        if (null != title && !("".equals(title))) {
            exceptSelectSQL.append(" and title like ? ");
            params.add('%' + title.trim() + '%');
        }

        if (null != discount && !("".equals(discount))) {
            exceptSelectSQL.append(" and discount = ? ");
            params.add(discount);
        }

        exceptSelectSQL.append(" order by update_time desc ");
        Page<Record> recordList = null;
        if (params.size() == 0) {
            recordList = Db.paginate(pageNumber, pageSize, "select * ", exceptSelectSQL.toString());
        }else {
            recordList = Db.paginate(pageNumber, pageSize, "select * ", exceptSelectSQL.toString(),params.toArray());
        }

        Map<String, Object> returnMap = new HashMap<String, Object>();
        returnMap.put("total", recordList.getTotalRow());
        returnMap.put("rows", recordList.getList());
        renderJson(returnMap);
    }

    @Before(Tx.class)
    public void save(){
        String id = this.getPara("id");
        String title = this.getPara("title");
        BigDecimal lowerLimit = new BigDecimal(this.getPara("lower_limit").toString());
        BigDecimal upperLimit = new BigDecimal(this.getPara("upper_limit").toString());
        Double discount = NumberUtil.toDouble(this.getPara("discount"));
        String comment = this.getPara("comment");
        Date currentDate = DateUtil.getCurrentDate();

        // 先判断输入的人数上限和人数下限是否符合规则
        if(lowerLimit.compareTo(upperLimit) > 0){
            renderJson(new JsonResult().status("-1").show("人数下限不能大于人数上限"));
            return;
        }

        // 若有ID, 则表明是更新操作。
        Record record = Db.findById("t_group_purchase_param",id);

        // 若ID为空，为新增操作，要初始化状态和创建时间。
        if (StringUtil.isEmpty(id)) {
            record = new Record();
            record.set("param_status",1);
            record.set("create_time",new Date());
        }

        // 新增和更新操作，都要修改以下信息。
        record.set("title", title)
                .set("lower_limit",lowerLimit)
                .set("upper_limit",upperLimit)
                .set("discount",discount)
                .set("comment",comment)
                .set("update_time",currentDate);

        if (StringUtil.isEmpty(id)) {
            if(!(Db.save("t_group_purchase_param", record))){
                renderJson(new JsonResult().status("-1").show("保存失败"));
            };
        }else {
            if (!Db.update("t_group_purchase_param",record)) {
                renderJson(new JsonResult().status("-1").show("保存失败"));
            }
        }
        renderJson(new JsonResult().status("000").show("保存成功"));
    }

    @Before(Tx.class)
    public void batchDelete(){
        String groupPurchaseIdList = getPara("selectRowsList");
        JsonResult result = new JsonResult();
        if (StringUtil.isEmpty(groupPurchaseIdList)) {
            renderJson(result.status("001").show("删除失败"));
            return;
        }

        StringBuilder deleteSQL = new StringBuilder("delete from t_group_purchase_param where id in (");
        Object [] tips = new Object[groupPurchaseIdList.split(",").length];
        int index = 0;
        for (String id : groupPurchaseIdList.split(",")) {
            deleteSQL.append("?,");
            tips[index]= id;
            index ++;
        }
        deleteSQL.deleteCharAt(deleteSQL.length() - 1).append(")");
        boolean deleteResult = Db.update(deleteSQL.toString(),tips) == tips.length;

        renderJson(deleteResult ? result.status("000").show("删除成功"):result.status("002").show("删除失败"));
    }

    @Before(Tx.class)
    public void toggleGroupPurchaseStatus(){
        String groupPurchaseIdList = getPara("selectRowsList");
        String paramStatus = getPara("paramStatus");
        JsonResult result = new JsonResult();
        if (StringUtil.isEmpty(groupPurchaseIdList)) {
            renderJson(result.status("001").show("操作失败"));
            return;
        }

        // 转换团购配置的状态
        paramStatus = ("enable".equals(paramStatus))? "1" : "0";

        StringBuilder exeSQL = new StringBuilder("update t_group_purchase_param set param_status = " + paramStatus + " where id in (");
        Object [] tips = new Object[groupPurchaseIdList.split(",").length];
        int index = 0;
        for (String id : groupPurchaseIdList.split(",")) {
            exeSQL.append("?,");
            tips[index]= id;
            index ++;
        }
        exeSQL.deleteCharAt(exeSQL.length() - 1).append(")");
        boolean updateResult = Db.update(exeSQL.toString(),tips) == tips.length;

        renderJson(updateResult ? result.status("000").show("操作成功"):result.status("001").show("操作失败"));
    }

}

